// pages/operation/addFeed/addFeed.js
var Zan = require('../../../dist/index');
var app = getApp();
var requestUrl = app.globalData.requestUrl;
const Util = require('../../../utils/util.js');
if (wx.canIUse('getRecorderManager')) {
	var recorderManager = wx.getRecorderManager();
}
var interval;
Page(Object.assign({}, Zan.CheckLabel, Zan.TopTips, {

  /**
   * 页面的初始数据
   */
  data: {
		cursorSpacing: 80,
		showConfirm: false,
		content: "",
		typeList: [
			{
				value: '4',
				name: '缺陷报告'
			},
			{
				value: '1',
				name: '业务开通'
			},
			{
				value: '2',
				name: '数据运维'
			},
			{
				value: '3',
				name: '需求申请'
			}
			
		],
		maxCount: 3, // 最大上传张数
		imgList: [],
		btnName: "提交",
		feedBackType: "4",
		id: "", // 默认空值, 有值说明是编辑功能, 值为消息id
		disabled: false,
		btnClass: 'zan-btn zan-btn--primary',
		showPopup: false,
		recorderFlag: "done",
		speakText: ""
  },
	inputContent: function (e) {
		var content = e.detail.value;
		this.setData({
			content: content
		})
	},
	radioChange: function (e) {
		var feedBackType = e.detail.value;
		this.setData({
			feedBackType: feedBackType
		})
	},
	getPhotos: function (id) {
		
		var that = this;
		wx.request({
			url: requestUrl + 'mui/showPhoto',
			method: 'GET',
			dataType: 'json',
			data: {
				id: id
			},
			header: {
				'content-type': 'application/json'
			},
			success: function (res) {
				
				var data = res.data;
				console.log(JSON.stringify(data))
				var attachment = data.photourl;
				if (attachment == "") { // 如果图片为空以下代码不执行
					return false;
				}
				var path = attachment.split('|');
				for (let i = 0; i < path.length; i++) {
					var attachmentPath = requestUrl + path[i];
					var imgList = that.data.imgList;

					wx.downloadFile({
						url: attachmentPath,
						success: function (res) {
							imgList.push(res.tempFilePath);
							that.setData({
								imgList: imgList
							});
						},
						fail: function () {
							console.log("下载失败")
						}
					})
				}
			},
			fail: function () {

			}
		})
	},
	addImg: function () {
		var that = this;
		var maxCount = this.data.maxCount;
		var imgCount = this.data.imgList.length;
		var count = maxCount - imgCount;
		wx.chooseImage({
			count: count,
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: function (res) {
				// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
				var tempFilePaths = res.tempFilePaths
				console.log(tempFilePaths);
				var imgList = that.data.imgList;
				for (let i = 0; i < tempFilePaths.length; i++ ) {
					imgList.push(tempFilePaths[i]);
				}
				that.setData({
					imgList: imgList
				});
			}
		})
	},
	preview: function (event) {
		var url = event.currentTarget.dataset.url;
		var imgUrls = this.data.imgList;
		wx.previewImage({
			current: url, // 当前显示图片的http链接
			urls: imgUrls // 需要预览的图片http链接列表
		})
	},
	remove: function (event) {
		var index = event.currentTarget.dataset.index;
		var imgList = this.data.imgList;
		imgList.splice(index, 1);
		this.setData({
			imgList: imgList
		});
	},
	formSubmit: function (e) {
		var formid = e.detail.formId;
		var content = this.data.content;
		if (content.trim() == "") {
			this.showZanTopTips("文字说明不能为空");
			return;
		}
		this.setData({
			disabled: true,
			btnClass: 'zan-btn zan-btn--default'
		});
		wx.showLoading({
			title: '提交中',
			mask: true
		})
		this.send(formid);
	},
	send: function (formid) {
		console.log(formid)
		var that = this;
		var imgList = this.data.imgList;
		var timestamp = Util.getTimestamp();
		console.log(timestamp)
		
		if (imgList.length == 0) {
			this.formSend(formid, timestamp, imgList.length);
		} else {
			console.log("有文件")
			var comNum = 0;
			console.log("timestamp: "+timestamp)
			console.log("图片数量: "+imgList.length);
			
			for (let i = 0; i < imgList.length; i++ ) {
				console.log("timestamp: " + timestamp)
				console.log("一共 " + imgList.length+"张图片, 正在传第 "+ i+1+ "张")
				wx.uploadFile({
					url: requestUrl + 'mui/raisePhoto',
					filePath: imgList[i],
					name: 'file',
					formData: {
						'timestamp': timestamp
					},
					success: function (res) {
						console.log(JSON.parse(res.data))
					},
					fail: function (err) {
						console.log("第"+i+"张上传失败: "+ err)
					},
					complete: function () {
						comNum++;
						if (comNum == imgList.length) {
							that.formSend(formid, timestamp, imgList.length)
						}
					}
				})
			}
		}
		
	},
	formSend: function (formid, timestamp, attachment) {
		console.log("表单内容开始提交")
		var that = this;
		var account = wx.getStorageSync('phone');
		var sibrccode = wx.getStorageSync('sibrccode');
		var userid = wx.getStorageSync('userid');
		var content = this.data.content;
		var feedBackType = this.data.feedBackType;
		var id = this.data.id;
		console.log("timestamp: " + timestamp)
		console.log("account: " + account + "," + "sibrccode: " + sibrccode + "," + "userid: " + userid + "," + "content: " + content + "," + "feedBackType: " + feedBackType+","+"id: " + id)
		wx.request({
			url: requestUrl + 'mui/raiseQuestion',
			method: 'POST',
			dataType: 'json',
			data: {
				content: content, // 内容描述
				feedBackType: feedBackType, // 反馈类别
				username: account,
				sibrccode: sibrccode,
				timestamp: timestamp,
				userid: userid,
				formid: formid,
				id: id,
				attachment: attachment
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			success: function (res) {
				wx.hideLoading()
				var data = res.data;
				console.log("返回数据data: " + JSON.stringify(data))
				if (data.result == 'true') {
					wx.showToast({
						title: '提交完成喽~',
						mask: true,
						duration: 2000
					})
					setTimeout(() => {
						if (id == "") {
							wx.navigateBack({
								delta: 1
							})
						} else {
							wx.navigateBack({
								delta: 2
							})
						}

					}, 1500);
				} else {
					that.showZanTopTips(data.message);
				}
				that.setData({
					disabled: false,
					btnClass: 'zan-btn zan-btn--primary'
				});
			},
			fail: function () {
				wx.hideLoading()
				that.setData({
					disabled: false,
					btnClass: 'zan-btn zan-btn--primary'
				});
			}
		})
	},
	togglePopup: function () { // 开始
		this.setData({
			showPopup: true
		})
		var that = this;
		var text = ['.','..','...','....','.....','......'];
		var i = 0;
		if (interval) {
			clearInterval(interval);
		}
		interval = setInterval( () => {
			if (i < 6) {
				that.setData({
					speakText: text[i]
				});
				i++;
			} else {
				i = 0;
			}
		}, 500)
	},
	startRecord: function () { // 开始录音
		var that = this;
		console.log(wx.canIUse('getRecorderManager'))
		console.log(recorderManager)
		if (!wx.canIUse('getRecorderManager')) {
			wx.showModal({
				title: '提示',
				content: '您的微信版本不支持此功能, 请更新微信重试',
				showCancel: false,
				success: function (res) {
					
				}
			})
			return false;
		}
		recorderManager = wx.getRecorderManager()
		this.togglePopup(); 
		this.setData({
			recorderFlag: "done"
		})
		// 配置
		const options = {
			duration: 60000,
			sampleRate: 16000,
			// encodeBitRate: 96000,
			numberOfChannels: 1,
			format: 'aac'
		}

		recorderManager.start(options); // 开始
		recorderManager.onStart(() => {
			console.log('recorder start')
		});

		recorderManager.onStop((res) => {
			if (interval) {
				clearInterval(interval);
			}
			that.setData({
				showPopup: false
			});
			console.log("停止: " + that.data.showPopup)
			console.log('recorder stop', res)
			const { tempFilePath } = res
			console.log("tempFilePath: " + tempFilePath)
			console.log("recorderFlag: " + this.data.recorderFlag)
			var content = this.data.content;
			if (that.data.recorderFlag == "done") {
				wx.showLoading({
					title: '翻译中...',
					mask: true
				})
				wx.uploadFile({
					url: requestUrl + 'mui/audioConversion',
					filePath: tempFilePath,
					name: 'file',
					success: function (res) {
						console.log(res)
						var data = JSON.parse(res.data);
						console.log(data)

						if (data.result == 'true') {
							content += data.message;
							that.setData({
								content: content
							});
						} else {
							wx.showToast({
								title: '文字转换失败',
								image: '../../../images/error.png',
								duration: 2000
							})
						}
					},
					complete: function () {
						wx.hideLoading()
					}
				})
			}
		})
		//错误回调
		recorderManager.onError((res) => {
			if (interval) {
				clearInterval(interval);
			}
			that.setData({
				recorderFlag: "cancel",
				showPopup: false
			});
			console.log(JSON.stringify(res.errMsg));
			// that.cancelRecord();
			wx.showModal({
				title: '提示',
				content: '录音失败: ' + res.errMsg,
				showCancel: false,
				success: function (res) {
					
				}
			})
		})

	},
	cancelRecord: function () { // 取消录音
		console.log("asdf")
		recorderManager.stop();
		if (interval) {
			clearInterval(interval);
		}
		this.setData({
			recorderFlag: "cancel",
			showPopup: false
		});
	},
	stopRecord: function () { // 录音完成
		var that = this;
		recorderManager.stop();
		this.setData({
			recorderFlag: "done",
			showPopup: false
		});
		
	},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
		
		var id = options.id;
		console.log(id)
		if (id == undefined) {
			return;
		}
		this.getPhotos(id);
		this.setData({
			id: options.id
		});
		try {
			var msgs = wx.getStorageSync('feedMsg')
			var content = "";
			var feedBackType = "0";
			if (msgs) {
				for (let i = 0; i < msgs.length; i++) {
					if (msgs[i].feedId == id) {
						content = msgs[i].content;
						feedBackType = msgs[i].feedType;
						console.log(msgs[i])
						this.setData({
							content: content,
							feedBackType: feedBackType
						});
						break;
					}
				}
			}
		} catch (e) {
			// Do something when catch error
		}
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
		var that = this;
		
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
		return {
			path: '/pages/sys/login/login',
			success: function (res) {
				// 转发成功
			},
			fail: function (res) {
				// 转发失败
			}
		}
  }
}))